﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using OOAD_Project_Engine.Foundation;
using OOAD_Project_Engine.Application.Services;
using Microsoft.Xna.Framework;

namespace OOAD_Project_Engine.Domain.Components
{
    public class Sprite : DrawableContent
    {
        //=============================
        [ConstructorParameter(Index = 0)]
        public string Source { get; protected set; }//
        [ConstructorParameter(Index = 1)]
        public bool _fromContent {get;protected set;}//
        //=============================

        public Texture2D Texture { get; protected set; }
        public Vector2 Size { get; private set; }

        [ComponentProperty(Serializable = true)]
        public Vector2 Origin { get; set; }


        public Sprite(string source, bool fromContent)
        {
            Source = source;
            _fromContent = fromContent;
            Origin = Vector2.Zero;
        }

        public override void LoadContent()
        {
            base.LoadContent();
            if (Source.Length == 0)
                throw new Exception("empty source");
            if (_fromContent)
                Texture = GameHelper.GetService<IContentService>().Load<Texture2D>(Source);
            else
                Texture = GameHelper.GetService<IContentService>().LoadFromFile<Texture2D>(Source);
            Size = new Vector2(Texture.Width, Texture.Height);
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        {
            Matrix m = Matrix.Identity;
            if (Owner.Contains<Transform>())
            {
                Transform transform = Owner.Find<Transform>();
                m = transform.World;
            }
            SpriteBatch sp = GameHelper.GetService<IGraphicService>().SpriteBatch;
            Graphic.DrawTexture(sp, Texture, Size * Origin, m);
        }

        public override object Clone()
        {
            Sprite s = new Sprite(Source, _fromContent);
            s.Origin = Origin;
            s.Visible = Visible;
            return s;
        }
    }
}
